﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Windows.Forms;

namespace Stark_VK_Video
{
    class VK_API
    {
        private Form MainForm;
        private string access_token = null;
        private string user_id = null;

        const int AppID = 3425665;
        const string vkMethodURL = "https://api.vk.com/method/";

        public string AccessToken
        {
            get { return this.access_token; }
        }
        public string UserID
        {
            get { return this.user_id; }
        }

        public VK_API(Form MainForm)
        {
            this.MainForm = MainForm;
        }

        public bool isAuthorized()
        {
            if (access_token == null || user_id == null) return false;

            string profiles = vkMethodURL + "getProfiles?uid=1&access_token=" + access_token;

            System.Net.WebRequest reqGET = System.Net.WebRequest.Create(profiles);
            System.Net.WebResponse resp = reqGET.GetResponse();
            System.IO.Stream stream = resp.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            string s = sr.ReadToEnd();

            JObject o = JObject.Parse(s);
            JObject error = (JObject)o["error"];

            if (error == null) return true;
            else return false;
        }

        public bool Authorize()
        {
            if (isAuthorized()) return true;
            LoginForm loginform = new LoginForm();
            WebBrowser browser = (WebBrowser)loginform.Controls["LoginBrowser"];
            browser.Navigated += new WebBrowserNavigatedEventHandler(Authorize_proceed);
            browser.Navigate("https://oauth.vk.com/authorize?client_id=" + AppID.ToString() +
                "&scope=photos,video&redirect_uri=" +
                "https://oauth.vk.com/blank.html&display=popup&response_type=token&hash=0");
            loginform.ShowDialog();

            if (access_token == null || user_id == null)
            {
                MessageBox.Show("Авторизация не пройдена!\r\nДля работы программы вы должны авторизироваться!\r\nЗапрос авторизации появится автоматически.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else return true;
        }

        private void Authorize_proceed(object sender, WebBrowserNavigatedEventArgs e)
        {
            string[] parts = e.Url.AbsoluteUri.Split('#');
            WebBrowser browser = (WebBrowser)sender;
            LoginForm loginform = (LoginForm)browser.Parent;

            if (parts[0] == "https://oauth.vk.com/blank.html")
            {
                if (parts[1].Substring(0, 5) == "error") loginform.Close();

                else if (parts[1].Substring(0, 12) == "access_token")
                {
                    //MessageBox.Show("Complete!");
                    parts = parts[1].Split('&');

                    access_token = parts[0].Split('=')[1];
                    user_id = parts[2].Split('=')[1];
                    loginform.Close();
                }
            }
            else
            {
                parts = e.Url.AbsoluteUri.Split('?');
                if (parts[0] == "https://oauth.vk.com/grant_access")
                    browser.Navigate("https://oauth.vk.com/authorize?client_id=" + AppID.ToString() + "&scope=photos&redirect_uri=https://oauth.vk.com/blank.html&display=popup&response_type=token&hash=0");
            }
        }

        public string[] GetMyProfile()
        {
            if (Authorize())
            {
                string profiles = vkMethodURL + "getProfiles?uid=" + user_id + "&fields=photo_medium_rec,sex,bdate,online&access_token=" + access_token;

                System.Net.WebRequest reqGET = System.Net.WebRequest.Create(profiles);
                System.Net.WebResponse resp = reqGET.GetResponse();
                System.IO.Stream stream = resp.GetResponseStream();
                System.IO.StreamReader sr = new System.IO.StreamReader(stream);
                string s = sr.ReadToEnd();

                JObject o = JObject.Parse(s);
                JArray response = (JArray)o["response"];

                string[] profile = new string[3];
                profile[0] = (string)response[0]["first_name"];
                profile[1] = (string)response[0]["last_name"];
                profile[2] = (string)response[0]["photo_medium_rec"];

                return profile;
            }
            else 
            { 
                string[] profile = new string[3];
                return profile;
            }
        }

        public string[][] GetMyVideos()
        {

            string profiles = vkMethodURL + "video.get?uid=" + user_id + "&access_token=" + access_token;
            System.Net.WebRequest reqGET = System.Net.WebRequest.Create(profiles);
            System.Net.WebResponse resp = reqGET.GetResponse();
            System.IO.Stream stream = resp.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            string s = sr.ReadToEnd();
            JObject o = JObject.Parse(s);
            JArray response = (JArray)o["response"];
            int video_count = (int)response[0];

            string[][] video_data = new string[video_count][];

            for (int i = 1; i < video_count; i++)
            {
                video_data[i] = new string[3];
                video_data[i][0] = (string)response[i]["title"];
                video_data[i][1] = (string)response[i]["image"];
                video_data[i][2] = (string)response[i]["player"];
            }

            return video_data;
        }

        public string[][] GetSearchVideos(string request)
        {
            string search_url = vkMethodURL + "video.search?q=" + request + "&access_token=" + access_token;
            System.Net.WebRequest reqGET = System.Net.WebRequest.Create(search_url);
            System.Net.WebResponse resp = reqGET.GetResponse();
            System.IO.Stream stream = resp.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            string s = sr.ReadToEnd();
            JObject o = JObject.Parse(s);
            JArray response = (JArray)o["response"];
            int video_count = response.Count;

            string[][] video_data = new string[video_count][];

            
            for (int i = 1; i < video_count; i++)
            {
                video_data[i] = new string[3];
                video_data[i][0] = (string)response[i]["title"];
                video_data[i][1] = (string)response[i]["thumb"];
                video_data[i][2] = (string)response[i]["player"];
            }
            return video_data;
        }
    }
}
